package com.ikas.ai.server.config;

import com.ikas.ai.utils.AppContextUtil;
import com.ikas.ai.utils.NumUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;

@Configuration
public class EnvConfig implements EnvironmentAware {

    private static Logger logger = LoggerFactory.getLogger(EnvConfig.class);
    private static Environment environment;
    private static String appSeverName = "server";
    private static int appSeverPort = 80;
    private static boolean isDebug = false;
    private static String title = "设备运行状态过程建模系统";

    @Override
    public synchronized void setEnvironment(Environment environment) {
        EnvConfig.environment = environment;
    }

    @PostConstruct
    public void init() {
        String str = environment.getProperty("spring.application.name");
        if (StringUtils.isNotBlank(str)) {
            setAppSeverName(str.trim());
        }
        str = environment.getProperty("server.port");
        if (StringUtils.isNotBlank(str) && !NumUtil.isInteger(str, 0, 65535)) {
            setAppSeverPort(Integer.parseInt(str.trim()));
        }
        str = environment.getProperty("spring.profiles.active");
        logger.debug("Property `spring.profiles.active` is {}", str);
        if (StringUtils.isNotBlank(str)) {
            setIsDebug(str.trim().toLowerCase().equalsIgnoreCase("dev"));
        }
    }

    /**
     * 从Nacos中获取配置信息
     *
     * @param key
     * @return
     */
    public static String getConfig(String key) {
        return getConfig(key, null);
    }

    /**
     * 从Nacos中获取配置信息
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getConfig(String key, String defaultValue) {
        String str = AppContextUtil.getContext().getEnvironment().getProperty(key);
        return StringUtils.isBlank(str) ? defaultValue : str.trim();
    }

    private synchronized void setAppSeverName(String value) {
        appSeverName = value;
    }

    private synchronized void setAppSeverPort(int value) {
        appSeverPort = value;
    }

    private synchronized void setIsDebug(boolean value) {
        isDebug = value;
    }

    /**
     * 获取微服务名称
     *
     * @return
     */
    public static synchronized String getAppSeverName() {
        return appSeverName;
    }

    /**
     * 获取微服务名称
     *
     * @return
     */
    public static synchronized int getAppSeverPort() {
        return appSeverPort;
    }

    /**
     * 获取当前配置状态
     *
     * @return
     */
    public static synchronized boolean isDebug() {
        return isDebug;
    }

    public static synchronized String getTitle() {
        return getConfig("app.title", title);
    }
}
